package com.szh.zx.javacorecorret.chap2.two;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

// 章节 2.2.5
// 方法 cyclicBarrier.getParties() -
// getNumberWaiting()-- 在屏障出等待的线程个数
public class CyclicBarrierTest6 {

	public static void main(String[] args) throws InterruptedException {
		MyService6 service =new MyService6();

		MyThreadC a = new MyThreadC(service);
		a.setName("A");
		MyThreadC b = new MyThreadC(service);
		a.setName("B");
		MyThreadC c = new MyThreadC(service);
		a.setName("C");

		a.start();
		b.start();
		c.start();

		Thread.sleep(2000);

		System.out.println("屏障对象的 parties 个数为："+service.cyclicBarrier.getParties());
		System.out.println("在屏障出等待的线程个数为："+service.cyclicBarrier.getNumberWaiting());
	}
}
class MyService6{
	public void testMethod(){
		try {
			System.out.println(Thread.currentThread().getName() + "准备 " + System.currentTimeMillis());
			if ("C".equals(Thread.currentThread().getName())){
				Thread.sleep(Integer.MAX_VALUE);
			}
			cyclicBarrier.await();
			System.out.println(Thread.currentThread().getName() + "开始 " + System.currentTimeMillis());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			e.printStackTrace();
		}
	}
	public CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() {
		@Override
		public void run() {
			System.out.println(Thread.currentThread().getName() + "   彻底结束了 " + System.currentTimeMillis());
		}
	});
}
class MyThreadE extends Thread{
	MyService6 service =new MyService6();

	@Override
	public void run() {
		service.testMethod();
	}

	public MyThreadE(MyService6 service) {
		this.service = service;
	}
}
class MyThreadF extends Thread{
	MyService6 service =new MyService6();

	@Override
	public void run() {
		service.testMethod();
	}

	public MyThreadF(MyService6 service) {
		this.service = service;
	}
}
class MyThreadC extends Thread{
	MyService6 service =new MyService6();

	@Override
	public void run() {
		service.testMethod();
	}

	public MyThreadC(MyService6 service) {
		this.service = service;
	}
}